/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.netcracker.test.eleven;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author I
 */
public class MyLockReentrant {
    static int count_lock = 0;
    static String name = null;
    public void Lock(){
        if(name == null){
            count_lock++;
            name = Thread.currentThread().getName();
        }
        else if(name.equals(Thread.currentThread().getName())){
            count_lock++;
        }
        else{
            try {
                synchronized(this){
                    Thread.currentThread().wait();
                }
                } catch (InterruptedException ex) {
                Logger.getLogger(MyLock.class.getName()).log(Level.SEVERE, null, ex);
                }
        }
           
    }
    
    public void unLock(){
        
        if(name!=null){
            if(count_lock > 1){
                count_lock--;
            }
            else{
                name = null;
                count_lock = 0;
                synchronized(this){
                    notifyAll();
                }
            }
        }
    }
    
    public boolean tryLock(){ 
        if(name==null){
            name = Thread.currentThread().getName();
            return true;
        }
        else if(name.equals(Thread.currentThread().getName())){
            count_lock++;
            return true;
        }
        else{
            return false;
        }
    }
    public boolean tryLock(long millisec){
        long count=0;
        boolean flag = false;
        
        while(true){
            try {
                if(count>=millisec)
                    break;
                TimeUnit.MILLISECONDS.sleep(1);
                
                if(name==null){
                    name = Thread.currentThread().getName();
                    return true;
                }
                else if(name.equals(Thread.currentThread().getName())){
                    count_lock++;
                    return true;
                }
                
            } catch (InterruptedException ex) {
                Logger.getLogger(MyLock.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return flag;
    }
}
